package com.dxyxx.framework;

import java.lang.ref.WeakReference;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import zrc.widget.ZrcListView;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import br.com.pierry.simpletoast.SimpleToast;

import com.android.customized.PullDownView;
import com.dxyxx.R;
import com.dxyxx.android.setting.UserPreferences;
import com.dxyxx.db.DataChangeProvider;
import com.dxyxx.db.DataQueryUtils;
import com.dxyxx.db.ShoppingCarContentObserver;
import com.dxyxx.pojo.User;

/**
 * shoppingcar 购物车没有 上下拉刷新功能。 我们做一个 实时刷新功能。
 * 
 * @author Administrator
 * 
 */

public class ShoppingCarFragment extends BaseFragment {
	private final static String ID = "id";
	private final static String PID = "pid";
	private final static String DESCRIPTION = "description";
	private final static String SPECIFICATION = "specification";
	private final static String PRICE = "price";
	private final static String THUMB = "thumb";
	private final static String IMAGEIDS = "imageIds";
	private final static String AMOUNT = "amount";
	private ViewHolder holder = null; // 如果缓存convertView为空，则需要创建View
	protected UserPreferences userPreferences;
	private TextView money;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.activity_shoppingcar, container, false);

		initViews(view);
		setGrid(view);
		Button button = (Button) view.findViewById(R.id.paynow);
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if ("0.00".equals(money.getText().toString())) {
					SimpleToast.info(getActivity(), "购物车没有物品");
					return;
				}
				User user = userPreferences.getCurrentUser();
				if (!user.isLogin()) {
					Intent intent = new Intent(getActivity(), LoginActivity.class);
					intent.putExtra("relogin", false);
					startActivity(intent);
				} else {
					startActivity(new Intent(getActivity(), OrderConfirmActivity.class));
				}
			}
		});
		return view;
	}

	public void initViews(View view) {
		((ImageView) view.findViewById(R.id.backImageButton)).setVisibility(View.INVISIBLE);
		((ImageView) view.findViewById(R.id.nextImageButton)).setVisibility(View.INVISIBLE);
		((TextView) view.findViewById(R.id.title)).setText("购物车");
		money = (TextView) view.findViewById(R.id.money);
		userPreferences = UserPreferences.getInstance(getActivity());

	}

	public class ShoppingCarAdapter extends BaseAdapter {
		private List<Map<String, String>> data;

		public ShoppingCarAdapter(Context context, List<Map<String, String>> data) {
			this.mInflater = LayoutInflater.from(context);
			this.data = data;
		}

		// ViewHolder静态类
		private LayoutInflater mInflater = null;

		/*
		 * public MessageAdapter(Context context) { this.mInflater =
		 * LayoutInflater.from(context); }
		 */

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			holder = null;

			int type = getItemViewType(position);
			if (convertView == null) {// 如果缓存convertView为空，则需要创建View
				holder = new ViewHolder();
				// 根据自定义的Item布局加载布局
				convertView = mInflater.inflate(R.layout.item_shoppingcar_list, null);
				holder.descriptionText = (TextView) convertView.findViewById(R.id.description);
				holder.specificationText = (TextView) convertView.findViewById(R.id.specification);
				holder.priceText = (TextView) convertView.findViewById(R.id.price);
				holder.thumbImage = (ImageView) convertView.findViewById(R.id.thumb);
				holder.addButton = (Button) convertView.findViewById(R.id.add);
				holder.minusButton = (Button) convertView.findViewById(R.id.minus);
				holder.amount = (TextView) convertView.findViewById(R.id.amount);

				convertView.setTag(holder);
			}
			Map<String, String> map = this.data.get(position);

			holder = (ViewHolder) convertView.getTag();
			holder.descriptionText.setText(map.get(DESCRIPTION));
			holder.specificationText.setText(map.get(SPECIFICATION));
			holder.amount.setText(map.get(AMOUNT));
			holder.priceText.setText(map.get(PRICE));
			holder.addButton.setOnClickListener(new AddClickListener(holder.amount, map));
			holder.minusButton.setOnClickListener(new MinusClickListener(holder.amount, map));

			imageLoader.displayImage(map.get(THUMB), holder.thumbImage, squareOptions, animateFirstListener);

			return convertView;
		}

		@Override
		public int getCount() {
			return this.data.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}
	}

	class AddClickListener implements OnClickListener {
		private TextView tv;
		private Map<String, String> map;

		public AddClickListener(TextView tv, Map<String, String> map) {
			this.tv = tv;
			this.map = map;
		}

		@Override
		public void onClick(View arg0) {

			int temp = Integer.parseInt((tv.getText().toString())) + 1;
			if (temp >= 0) {
				tv.setText(temp + "");
				// 改变数据库。 update
				ContentValues contentValues = new ContentValues();
				int pid = Integer.parseInt(map.get(PID));
				contentValues.put("pid", pid);
				contentValues.put(DESCRIPTION, map.get(DESCRIPTION));
				contentValues.put(SPECIFICATION, map.get(SPECIFICATION));
				contentValues.put(PRICE, map.get(PRICE));
				contentValues.put(THUMB, map.get(THUMB));
				contentValues.put("amount", temp);
				map.put(AMOUNT, temp + "");
				getActivity().getContentResolver().update(Uri.parse("content://com.dxyxx/cart/" + pid), contentValues, null, null);

			}
			money.setText(getMoney());
		}

	}

	class MinusClickListener implements OnClickListener {
		private TextView tv;
		private Map<String, String> map;

		public MinusClickListener(TextView tv, Map<String, String> map) {
			this.tv = tv;
			this.map = map;

		}

		@Override
		public void onClick(View arg0) {
			int temp = Integer.parseInt((tv.getText().toString())) - 1;
			if (temp > 0) {
				tv.setText(temp + "");
				// 改变数据库。 update
				ContentValues contentValues = new ContentValues();
				int pid = Integer.parseInt(map.get(PID));
				contentValues.put("pid", pid);
				contentValues.put(DESCRIPTION, map.get(DESCRIPTION));
				contentValues.put(SPECIFICATION, map.get(SPECIFICATION));
				contentValues.put(PRICE, map.get(PRICE));
				contentValues.put(THUMB, map.get(THUMB));
				contentValues.put("amount", temp);
				map.put(AMOUNT, temp + "");
				getActivity().getContentResolver().update(Uri.parse("content://com.dxyxx/cart/" + pid), contentValues, null, null);

			} else if (temp == 0) {
				// 改变数据库。 delete
				ContentValues contentValues = new ContentValues();
				int pid = Integer.parseInt(map.get(PID));
				contentValues.put(PID, pid);
				contentValues.put(DESCRIPTION, map.get(DESCRIPTION));
				contentValues.put(SPECIFICATION, map.get(SPECIFICATION));
				contentValues.put(PRICE, map.get(PRICE));
				contentValues.put(THUMB, map.get(THUMB));
				contentValues.put(AMOUNT, temp);
				map.put(AMOUNT, temp + "");
				getActivity().getContentResolver().delete(Uri.parse("content://com.dxyxx/cart/" + pid), null, null);
			} else {

			}
			money.setText(getMoney());
		}

	}

	public String getMoney() {
		double m = 0;
		Cursor cursor = DataQueryUtils.getPriceAndAmount(getActivity());
		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
			Map<String, String> map = new HashMap<String, String>();

			int priceColumn = cursor.getColumnIndex(PRICE);
			int amountColumn = cursor.getColumnIndex(AMOUNT);

			m += Double.parseDouble((String) cursor.getString(priceColumn)) * cursor.getInt(amountColumn);
		}
		cursor.close();
		DecimalFormat df = new DecimalFormat("######0.00");
		return df.format(m);
	}

	static class ViewHolder {
		public TextView descriptionText;
		public TextView specificationText;
		public TextView priceText;
		public ImageView thumbImage;
		public Button addButton;
		public Button minusButton;
		public TextView amount;
	}

	private final static int COUNT = 5;
	private ShoppingCarAdapter commonAdapter;
	private ArrayList<String> msgs;
	private int pageId = -1;

	/** 被选中的. */
	private int gridID = -1;
	/** 每页显示的数量，Adapter保持一致. */
	private static final float PAGE_SIZE = 12.0f;
	/** GridView. */
	private GridView gridView;
	/** 自定义的左右滑动. */
	private ViewPager vp;
	/** 页码条布局. */
	private LinearLayout layoutBottom;

	/** 页码条. */
	private ImageView imgCur;
	// common private
	// private PullDownView commonView;
	private ListView commonLv;
	private PullDownView privateView;
	private ListView privateLv;
	private PullDownView otherView;
	private ListView otherLv;

	private List<View> list;

	private ZrcListView listView;
	private Handler handler;
	private List<Map<String, String>> shoppingCarData;

	public List<Map<String, String>> getShoppingCarData() {
		return shoppingCarData;
	}

	private void setGrid(View view) {

		// 在这里添加视图。多个自定义的View
		// 公共信息
		LayoutInflater mInflater = LayoutInflater.from(getActivity());
		// View commonList = mInflater.inflate(R.layout.shoppingcar_list, null);
		listView = (ZrcListView) view.findViewById(R.id.shoppingListView);
		handler = new Handler();
		shoppingCarData = new ArrayList<Map<String, String>>();
		money.setText(getMoney());
		Cursor cursor = DataQueryUtils.getAll(getActivity());
		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
			Map<String, String> map = new HashMap<String, String>();
			int descriptionColumn = cursor.getColumnIndex(DESCRIPTION);
			int thumbColumn = cursor.getColumnIndex(THUMB);
			int priceColumn = cursor.getColumnIndex(PRICE);
			int pidColumn = cursor.getColumnIndex(PID);
			int amountColumn = cursor.getColumnIndex(AMOUNT);
			int specificationColumn = cursor.getColumnIndex(SPECIFICATION);
			map.put(DESCRIPTION, cursor.getString(descriptionColumn));
			map.put(THUMB, cursor.getString(thumbColumn));
			map.put(PRICE, cursor.getString(priceColumn));
			map.put(AMOUNT, cursor.getInt(amountColumn) + "");
			map.put(PID, cursor.getInt(pidColumn) + "");
			map.put(SPECIFICATION, cursor.getString(specificationColumn) + "");
			shoppingCarData.add(map);
		}
		cursor.close();//千万记得要关闭啊
		commonAdapter = new ShoppingCarAdapter(getActivity(), shoppingCarData);

		// // 设置下拉刷新的样式（可选，但如果没有Header则无法下拉刷新）
		// SimpleHeader header = new SimpleHeader(getActivity());
		// header.setTextColor(0xff0066aa);
		// header.setCircleColor(0xff33bbee);
		// listView.setHeadable(header);
		//
		// // 设置加载更多的样式（可选）
		// SimpleFooter footer = new SimpleFooter(getActivity());
		// footer.setCircleColor(0xff33bbee);
		// listView.setFootable(footer);

		// 设置列表项出现动画（可选）
		// listView.setItemAnimForTopIn(R.anim.topitem_in);
		// listView.setItemAnimForBottomIn(R.anim.bottomitem_in);

		// 下拉刷新事件回调（可选）
		// listView.setOnRefreshStartListener(new OnStartListener() {
		// @Override
		// public void onStart() {
		// refresh();
		// }
		// });

		// 加载更多事件回调（可选）
		// listView.setOnLoadMoreStartListener(new OnStartListener() {
		// @Override
		// public void onStart() {
		// loadMore();
		// }
		// });
		listView.setDivider(getResources().getDrawable(R.color.common_list_devider_color));
		listView.setDividerHeight(2);
		listView.setAdapter(commonAdapter);

	}

	//** 避免  handler 内存泄露。 见http://stackoverflow.com/questions/11278875/handlers-and-memory-leaks-in-android
	static class MyInnerHandler extends Handler {
		WeakReference<ShoppingCarFragment> mFrag;

		MyInnerHandler(ShoppingCarFragment aFragment) {
			mFrag = new WeakReference<ShoppingCarFragment>(aFragment);
		}

		@Override
		public void handleMessage(Message message) {
			ShoppingCarFragment theFrag = mFrag.get();
			if (theFrag != null) {
				theFrag.shoppingCarData.clear();
				Cursor cursor = DataQueryUtils.getAll(theFrag.getActivity().getApplicationContext());
				double m = 0;
				for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
					Map<String, String> map = new HashMap<String, String>();
					int descriptionColumn = cursor.getColumnIndex(DESCRIPTION);
					int thumbColumn = cursor.getColumnIndex(THUMB);
					int priceColumn = cursor.getColumnIndex(PRICE);
					int amountColumn = cursor.getColumnIndex(AMOUNT);
					int pidColumn = cursor.getColumnIndex(PID);
					map.put(DESCRIPTION, cursor.getString(descriptionColumn));
					map.put(THUMB, cursor.getString(thumbColumn));
					map.put(PRICE, cursor.getString(priceColumn));
					map.put(AMOUNT, cursor.getInt(amountColumn) + "");
					map.put(PID, cursor.getInt(pidColumn) + "");
					theFrag.shoppingCarData.add(map);

					m += Double.parseDouble((String) cursor.getString(priceColumn)) * cursor.getInt(amountColumn);
				}
				cursor.close();//关闭查询
				DecimalFormat df = new DecimalFormat("######0.00");
				theFrag.money.setText(df.format(m));
				theFrag.commonAdapter.notifyDataSetChanged();
			}
		}
	}

	private MyInnerHandler myHandler = new MyInnerHandler(this);
	private ShoppingCarContentObserver shoppingCarContentObserver;

	@Override
	public void onResume() {

		super.onResume();
		if (shoppingCarContentObserver == null) {
			shoppingCarContentObserver = new ShoppingCarContentObserver(myHandler);
			getActivity().getContentResolver().registerContentObserver(DataChangeProvider.CONTENT_URI, true, shoppingCarContentObserver);
		}
		//设置监听
	}

	//删除监听..此处不能删除监听
	@Override
	public void onStop() {
		super.onStop();
		if (shoppingCarContentObserver != null) {
			//getActivity().getContentResolver().unregisterContentObserver(shoppingCarContentObserver);
		}
	}
}
